#!/usr/bin/env python3
"""
Demo script showing .env configuration usage
"""

import os
from pathlib import Path

def demo_env_configuration():
    """Demonstrate .env configuration capabilities"""
    print("🔧 Qwen3 Client .env Configuration Demo")
    print("=" * 50)
    
    # Check if .env file exists
    package_dir = Path(__file__).parent
    env_file = package_dir / ".env"
    
    print(f"📁 Package directory: {package_dir}")
    print(f"📄 .env file: {env_file}")
    print(f"✅ .env exists: {env_file.exists()}")
    
    if env_file.exists():
        print(f"\n📋 .env file contents:")
        with open(env_file, 'r') as f:
            content = f.read()
            # Mask API key for security
            masked_content = content.replace('sk-test-key-for-qwen3-client-package', 'sk-***-masked-***')
            print(masked_content)
    
    print("\n🚀 Testing auto-configuration...")
    
    # Test 1: Auto-config without explicit import
    try:
        from qwen3_client import Qwen3Config
        config = Qwen3Config.auto_config()
        print(f"✅ Auto-config successful")
        print(f"   Model: {config.model_name}")
        print(f"   Base URL: {config.base_url}")
        print(f"   Skip validation: {config.skip_validation}")
        print(f"   Max tokens: {config.max_tokens}")
    except Exception as e:
        print(f"❌ Auto-config failed: {e}")
    
    # Test 2: Quick setup
    try:
        from qwen3_client import quick_setup
        client, logger = quick_setup()
        print(f"✅ Quick setup successful")
        print(f"   Client initialized: {client is not None}")
        print(f"   Logger configured: {logger is not None}")
    except Exception as e:
        print(f"❌ Quick setup failed: {e}")
    
    # Test 3: Auto-create client
    try:
        from qwen3_client import Qwen3Client
        client = Qwen3Client.auto_create()
        print(f"✅ Auto-create client successful")
        print(f"   Skip validation: {client.config.skip_validation}")
        
        # Test validation (should be skipped)
        is_valid = client.validate_connection()
        print(f"   Connection validation: {is_valid}")
    except Exception as e:
        print(f"❌ Auto-create client failed: {e}")
    
    # Test 4: Mock response when no real API key
    try:
        print(f"\n🧪 Testing mock responses...")
        response = client.ask("What is data assimilation?")
        print(f"✅ Mock response received:")
        print(f"   Length: {len(response)} characters")
        print(f"   Content: {response[:100]}...")
    except Exception as e:
        print(f"❌ Mock response failed: {e}")
    
    # Test 5: Environment variable inspection
    print(f"\n🔍 Current environment variables:")
    qwen_vars = {k: v for k, v in os.environ.items() if k.startswith(('DASHSCOPE_', 'QWEN_'))}
    
    for key, value in qwen_vars.items():
        # Mask sensitive values
        if 'KEY' in key.upper():
            display_value = f"{value[:8]}***" if len(value) > 8 else "***"
        else:
            display_value = value
        print(f"   {key}: {display_value}")
    
    # Test 6: Configuration precedence
    print(f"\n📊 Testing configuration precedence...")
    
    # Show how CLI args would override .env
    from qwen3_client.core import Qwen3Config
    
    # Manual config with override
    custom_config = Qwen3Config(
        api_key="custom-key",
        model_name="custom-model",
        max_tokens=8192,
        skip_validation=False
    )
    print(f"✅ Custom config created:")
    print(f"   Model: {custom_config.model_name}")
    print(f"   Max tokens: {custom_config.max_tokens}")
    print(f"   Skip validation: {custom_config.skip_validation}")
    
    print(f"\n🎯 Usage patterns:")
    print("=" * 50)
    print("1. Zero-config usage:")
    print("   from qwen3_client import quick_setup")
    print("   client, logger = quick_setup()")
    print()
    print("2. Auto-config usage:")
    print("   from qwen3_client import Qwen3Client")
    print("   client = Qwen3Client.auto_create()")
    print()
    print("3. Manual override:")
    print("   config = Qwen3Config.auto_config()")
    print("   config.model_name = 'different-model'")
    print("   client = Qwen3Client(config)")
    print()
    print("4. CLI usage (auto-loads .env):")
    print("   qwen3-client ask 'What is machine learning?'")
    print()
    print("5. CLI with override:")
    print("   qwen3-client ask 'Question' --api-key your-key")
    
    print(f"\n✨ .env Configuration Benefits:")
    print("=" * 50)
    print("✅ No need to set environment variables manually")
    print("✅ Package works out-of-the-box")
    print("✅ API key validation can be skipped for testing")
    print("✅ All settings configurable in one place")
    print("✅ Local .env can override package .env")
    print("✅ CLI arguments override .env settings")
    print("✅ Mock responses available when no API key")


if __name__ == "__main__":
    demo_env_configuration()